﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Willow.MVC.Search
{
    public static class SearchExtension
    {
        /// <summary>
        /// 从指定IQueryable[T]集合 中查询子数据集
        /// </summary>
        /// <typeparam name="T">动态类型</typeparam>
        /// <param name="source">要查询的数据集</param>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        public static IQueryable<T> Where<T>(this IQueryable<T> source, QueryModel model)
        {
            if (model.Items.Count() != 0)
            {
                source = new QueryableSearcher<T>(source, model.Items).Search();
            }
            return source;
        }

        /// <summary>
        /// 从指定IQueryable[T]集合 中查询指定分页条件的子数据集
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The source.</param>
        /// <param name="model">The model.</param>
        /// <param name="pageIndex">Index of the page.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <param name="total">The total.</param>
        /// <returns></returns>
        public static IQueryable<T> Where<T>(this IQueryable<T> source, QueryModel model, int pageIndex, int pageSize,
            out int total)
        {
            if (model.Items.Count() != 0)
            {
                source = new QueryableSearcher<T>(source, model.Items).Search();
            }

            total = source.Count();
            return source != null
                ? source.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<T>().AsQueryable();
        }

    }
}
